/**
 * Created by Administrator on 2017/6/30.
 */
define(
    ['knockout',
        'platform.common',
        'bootbox',
        'knockout-bsTable',
        'knockout-jsTree',
        'knockout-component',
        'knockout.validate',
        'sco.msg'],
    function (ko, platform, bootbox) {
        /**
         * 后台方法调用
         * @type {{get: get, remove: remove, save: save}}
         */
        var rest = {
            get: function (permId) {
                var param = {};
                param.perm_id = permId;
                var result = platform.servicebreak('~/rest/perm/selectOne', param).responseJSON;
                return result;
            },
            remove: function (permId) {
                var param = {};
                param.perm_id = permId;
                platform.servicebreakAsync('~/rest/perm/delete', param, 'post')
                    .done(function (response) {
                        if (response instanceof Object && response.meta.success) {
                            platform.showOperTip('DELSUC');
                            viewModel.tableViewModel.refresh();
                        }
                    });
            },
            save: function (param) {//保存权限信息
                platform.servicebreakAsync('~/rest/perm/save', param, 'post',
                    function () {
                        platform.showOperTip('dealing');
                    }).done(function (response) {
                    if (response instanceof Object && response.meta.success) {
                        platform.showOperTip('savesuc');
                        viewModel.tableViewModel.refresh();
                    }

                });
            },
            saveGroupInfo: function (param) {//保存分组信息
                platform.servicebreakAsync('~/rest/perm/group/save', param, 'post',
                    function () {
                        platform.showOperTip('dealing');
                    }).done(function (response) {
                    if (response instanceof Object && response.meta.success) {
                        platform.showOperTip('savesuc');
                        // viewModel.tableViewModel.refresh();
                        //刷新树
                    }

                });
            },
            // getGroupInfo: function (param) {
            //
            // },
            deleteGroup: function (param) {//删除分组

            }
        };

        var kbTable = require('knockout-bsTable');
        var jsTree = require('knockout-jsTree');

        var ViewModel = function () {
            var self = this;

            self.selectedNode = ko.observable();
            self.treeViewModel = new jsTree.jsTreeViewModel({
                core: {
                    data: {
                        url: platform.mapUrl('~/rest/perm/group/loadGroupTree'),
                        dataType: 'json',
                        method: 'post'
                    },
                    types: {'default': {'icon': 'fa fa-bank'}}
                },
                plugins: ['wholerow', 'contextmenu'],
                contextmenu: {
                    items: {
                        create: {
                            label: '新增分组',
                            icon: 'fa fa-file-text-o',
                            separator_after: true,
                            action: function (data) {
                                var inst = $.jstree.reference(data.reference),
                                    obj = inst.get_node(data.reference);
                                var pId = obj.id;
                                var name = obj.text;
                                var parent = obj.parent;
                                debugger;
                                self.permGroupViewModel.showNewForm(pId, parent);
                            }
                        },
                        // edit: {
                        //     label: '编辑分组',
                        //     icon: 'fa fa-edit',
                        //     separator_after: true,
                        //     action: function (data) {
                        //
                        //     }
                        // },
                        remove: {
                            label: '删除分组',
                            icon: 'fa fa-trash',
                            action: function (data) {
                                var inst = $.jstree.reference(data.reference),
                                    obj = inst.get_node(data.reference);
                                var pId = obj.id;
                                var param = {};
                                param.perm_group_id = pId;
                                rest.deleteGroup(param);
                            }
                        }
                    }
                }
            });
            self.onTreeNodeSelected = function (event, data) {
                var param = {};
                if (data.node.parent == '#') {
                    param.perm_group_id = '';
                    self.selectedNode('');
                } else {
                    param.perm_group_id = data.node.id;
                    self.selectedNode(data.node.id);
                }
                self.tableViewModel.refresh(param);
            };
            self.columns = [
                {
                    checkbox: true,
                    align: 'center',
                    width: 30
                },
                {
                    field: 'display_order',
                    title: '序号',
                    formatter: function (value, row, index) {
                        var options = self.tableViewModel.getOptions();
                        var indexPageNum = parseInt(options.pageNumber);
                        var indexPageSize = parseInt(options.pageSize);
                        return ((indexPageNum - 1) * indexPageSize)
                            + (index + 1);
                    },
                    width: 35,
                    align: 'center'
                },
                {
                    field: 'perm_id',
                    title: '主键标识',
                    width: 120,
                    align: 'center',
                    visible: false
                }, {
                    field: 'perm_code',
                    title: '权限编码',
                    width: 80
                }, {
                    field: 'perm_name',
                    title: '权限名称',
                    align: 'left'
                }];
            self.tableViewModel = new kbTable.bootstrapTableViewModel({
                url: platform.mapUrl('~/rest/perm/list'),
                toolbar: '#toolbar',
                queryParams: function (params) {
                    return {
                        pageNumber: params.offset / params.limit + 1,
                        pageSize: params.limit
                    };
                },
                columns: self.columns
            });
            self.modalVisible = ko.observable(false);
            self.permViewModel = {
                title: ko.observable(),
                permId: ko.observable(),
                permName: ko.observable(),
                permCode: ko.observable(),
                appId: ko.observable(),
                editStatus: ko.observable(), // 默认数据状态
                recordStatus: ko.observable(), // 默认数据状态
                enabled: ko.observable(false), // 只读设置
                resetForm: function () {
                    $('#detailForm').resetForm();

                    this.title('');
                    this.permId('');
                    this.permCode('');
                    this.permName('');
                    this.appId('');
                    this.editStatus('');
                    this.recordStatus('');
                    this.enabled(true);
                },
                disableForm: function () {
                    $('#detailForm').find('input,textarea').attr('disabled', true);
                },
                enableForm: function () {
                    $('#detailForm').find('input,textarea').attr('disabled', false);
                },
                setFormData: function (permId) {
                    var result = rest.get(permId);
                    if (result instanceof Object && result.meta.success) {
                        var info = result.responseObject;
                        this.permId(info.perm_id);
                        this.permCode(info.perm_code);
                        this.permName(info.perm_name);
                    }
                },
                showNewForm: function () {
                    this.resetForm();
                    this.enableForm();

                    this.title('新增权限数据');
                    this.permId(platform.uuid());
                    this.editStatus('0');
                    self.modalVisible(true);
                },
                showEditForm: function (permId) {
                    this.resetForm();
                    this.enableForm();

                    this.title('编辑权限数据');
                    this.setFormData(permId);
                    self.modalVisible(true);
                },
                showViewForm: function (permId) {
                    this.resetForm();
                    this.disableForm();

                    this.title('查看权限数据');
                    this.setFormData(permId);
                    this.enabled(false);
                    self.modalVisible(true);
                },
                save: function () {
                    //是否经过表单校验
                    var param = {};
                    param.perm_id = this.permId();
                    param.perm_code = this.permCode();
                    param.perm_name = this.permName();

                    param.edit_status = this.editStatus();
                    if (param.edit_status == '0')//新增,新增时录应用ID
                    {
                        param.app_id = this.appId();
                        param.record_status = this.recordStatus();
                    }
                    rest.save(param);
                },
                close: function () {
                    self.modalVisible(false);
                    $('#permDialog').toggleClass('hide');
                }
            };
            self.pgModalVisible = ko.observable();
            self.permGroupViewModel = {
                title: ko.observable(''),
                permGroupId: ko.observable(),
                permGroupCode: ko.observable(),
                permGroupName: ko.observable(),
                pPermGroupId: ko.observable(),
                ppPGId: ko.observable(),
                resetForm: function () {
                    $('#groupDetailForm').resetForm();

                    this.title('');
                    this.permGroupId('');
                    this.permGroupCode('');
                    this.permGroupName('');
                },
                disableForm: function () {
                    $('#groupDetailForm').find('input,textarea').attr('disabled', true);
                },
                enableForm: function () {
                    $('#groupDetailForm').find('input,textarea').attr('disabled', false);
                },
                setFormData: function (groupId) {
                },
                showNewForm: function (pid, parent) {
                    this.resetForm();
                    this.title('新增权限分组');
                    this.permGroupId(platform.uuid());
                    this.pPermGroupId(pid);
                    this.ppPGId(parent);
                    self.pgModalVisible(true);
                    $('#permGroupDialog').toggleClass('hide');
                },
                showEditForm: function () {
                    this.resetForm();
                    $('#permGroupDialog').toggleClass('hide');
                },
                save: function () {
                    var param = {};
                    param.perm_group_id = this.permGroupId();
                    param.perm_group_code = this.permGroupCode();
                    param.perm_group_name = this.permGroupName();
                    param.p_perm_group_id = this.pPermGroupId();
                    param.p_p_perm_group_id = this.ppPGId();
                    rest.saveGroupInfo(param);
                },
                close: function () {
                    self.pgModalVisible(false);
                    $('#permGroupDialog').toggleClass('hide');
                }
            };
            self.fnSearch = function () {
                platform.showWarnTip('功能尚未开放...');
            };
            self.fnAdd = function () {
                self.permViewModel.showNewForm();
                $('#permDialog').toggleClass('hide');
            };
            self.fnEdit = function () {
                var selections = self.tableViewModel.getSelections();
            };
            self.fnView = function () {
                var selections = self.tableViewModel.getSelections();
            };
            self.fnRemove = function () {
                var selections = self.tableViewModel.getSelections();
                if (selections.length = 1) {
                    bootbox.confirm({
                        title: '删除提示',
                        size: 'small',
                        message: '是否删除该节点数据?',
                        buttons: {
                            confirm: {
                                label: '确认',
                                className: 'btn-success btn-sm'
                            },
                            cancel: {
                                label: '取消',
                                className: 'btn-default btn-sm'
                            }
                        },
                        callback: function (result) {
                            if (result) {
                                rest.remove(selections[0].perm_id);
                                self.tableViewModel.refresh();
                            }
                        }
                    });
                } else {
                    platform.showTip('REMOVE');
                }
            }
        };
        var viewModel = new ViewModel();
        return viewModel;
    });